package org.cx.oa.base;

import java.lang.reflect.ParameterizedType;
import java.util.Collections;
import java.util.List;

import org.cx.oa.util.HibernateSessionUtil;
import org.hibernate.Session;

@SuppressWarnings("unchecked")
public class BaseDaoImpl<T> implements BaseDao<T>{

	protected Class<T> clzz;
	public BaseDaoImpl(){
		ParameterizedType pt= (ParameterizedType) this.getClass().getGenericSuperclass();
		clzz=(Class<T>) pt.getActualTypeArguments()[0];
	}
	public void save(T obj) {
		getSession().save(obj);
		
	}

	@Override
	public void update(T obj) {
		getSession().update(obj);
		
	}

	@Override
	public void delete(T obj) {
		getSession().delete(obj);
	}

	@Override
	public List<T> findAll() {	
		List<T> list=getSession().createQuery("from "+clzz.getName()).list();
		return list;
	}

	
	@Override
	public T findById(int id) {
		return (T)getSession().createQuery("from "+clzz.getName()+" where id=:id")
		.setParameter("id", id).uniqueResult();
	}
	
	@Override
	public List<T> getByIdList(Integer[] idList) {
		if(idList == null || idList.length==0){
			return Collections.EMPTY_LIST;
		}
		return getSession().createQuery("from "+clzz.getName()+" where id in(:idList)")
		.setParameterList("idList", idList)
		.list();
	}
	
	@Override
	public Session getSession() {
		Session session=HibernateSessionUtil.getSession();
		if(session == null){
			session=HibernateSessionUtil.openSession();
			session.beginTransaction();
		}
		return session;
	}
	


}
